<template>
    <el-container class="zuiwaiceng">
        <el-header class="tou">
            <div class="page-header">
                <i class="el-icon-back" style="color: white; margin-right: 20px; margin-top: 18px; margin-left: 20px;"
                    @click="goback"></i>
                <el-dropdown style="float: right;">
                    <span class="el-dropdown-link"
                        style="float: right; font-size: 15px; color: white; margin-right: 25px; margin-top: 18px;">
                        <i class="el-icon-arrow-down el-icon--left"
                            style="float: right; color: white; margin-right: 5px; margin-top: 3px;"></i>超级管理员
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item icon="el-icon-user">切换账号</el-dropdown-item>
                        <el-dropdown-item icon="el-icon-circle-close">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </el-header>
        <el-main>
            <el-tabs v-model="activeName" :tab-position="tabPosition" @tab-click="handleClick">
                <el-tab-pane label="业务信息" name="first" style="margin-left:10px; margin-right:15px;">
                    <el-descriptions title="业务信息" direction="vertical" :column="4" border>
                        <el-descriptions-item label="表名" :span="3">{{ nowtable.TABLE_NAME }}</el-descriptions-item>
                        <el-descriptions-item label="中文名称" :span="1">{{ yewuList.metadata_cnname }}
                        </el-descriptions-item>
                        <el-descriptions-item label="负责人" :span="2">{{ yewuList.metadata_owner }}</el-descriptions-item>
                        <el-descriptions-item label="类型" :span="2">
                            <el-tag size="small">{{ yewuList.metadata_subarea }}</el-tag>
                        </el-descriptions-item>
                        <el-descriptions-item label="描述" :span="4">{{ nowtable.TABLE_COMMENT }}</el-descriptions-item>
                        <el-descriptions-item label="注意事项" :span="4">{{ yewuList.metadata_tip }}</el-descriptions-item>
                    </el-descriptions>
                    <el-button type="primary" @click="editYewu" style="margin-top: 20px;"><i class="el-icon-edit"></i>
                        编辑</el-button>
                    <el-button type="danger" @click="deleteTable"><i class="el-icon-delete"></i> 删除表</el-button>
                </el-tab-pane>
                <el-tab-pane label="字段信息" name="second">
                    <el-table :data="ziduanList" height="500" border style="width: 100%">
                        <el-table-column prop="COLUMN_NAME" label="字段名称" width="180">
                        </el-table-column>
                        <el-table-column prop="COLUMN_COMMENT" label="描述" width="180">
                        </el-table-column>
                        <el-table-column prop="DATA_TYPE" label="属性">
                        </el-table-column>
                        <el-table-column prop="IS_NULLABLE" :formatter="stateFormat2" label="能否为空">
                        </el-table-column>
                        <el-table-column prop="COLUMN_KEY" :formatter="stateFormat" label="主键">
                        </el-table-column>
                        <el-table-column prop="" label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="editCol(scope.$index, scope.row)">编辑</el-button>
                                <el-button size="mini" type="danger" @click="deleteCol(scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" @click="addCol" style="margin-top:15px"><i class="el-icon-plus"></i>新建字段
                    </el-button>
                </el-tab-pane>
                <!-- <el-tab-pane label="血缘分析" name="third">角色管理</el-tab-pane> -->
            </el-tabs>

            <!-- 新建字段对话框 -->
            <el-dialog title="新建字段" :visible.sync="addcolVisible">
                <el-form :model="colform">
                    <el-form-item label="字段名称" :label-width="formLabelWidth" required>
                        <el-input v-model="colform.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="属性" :label-width="formLabelWidth" required>
                        <el-select v-model="colform.type" placeholder="请选择属性">
                            <el-option label="int" value="int"></el-option>
                            <el-option label="float" value="float"></el-option>
                            <el-option label="double" value="double"></el-option>
                            <el-option label="char" value="char"></el-option>
                            <el-option label="varchar" value="varchar"></el-option>
                            <el-option label="date" value="date"></el-option>
                            <el-option label="time" value="time"></el-option>
                            <el-option label="datetime" value="datetime"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="长度" :label-width="formLabelWidth" required>
                        <el-input v-model="colform.col_length" autocomplete="off" placeholder="若类型为char或varchar则必填">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth" required>
                        <el-input v-model="colform.description" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="选项" :label-width="formLabelWidth">
                        <el-checkbox v-model="pri_checked">主键</el-checkbox>
                        <el-checkbox v-model="isnull_checked">非空</el-checkbox>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addcolVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addColSubmit">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 编辑字段对话框 -->
            <el-dialog title="编辑字段" :visible.sync="editcolVisible">
                <el-form :model="colform">
                    <el-form-item label="字段名称" :label-width="formLabelWidth" required>
                        <el-input v-model="colform.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="属性" :label-width="formLabelWidth" required>
                        <el-select v-model="colform.type" placeholder="请选择属性">
                            <el-option label="int" value="int"></el-option>
                            <el-option label="float" value="float"></el-option>
                            <el-option label="double" value="double"></el-option>
                            <el-option label="char" value="char"></el-option>
                            <el-option label="varchar" value="varchar"></el-option>
                            <el-option label="date" value="date"></el-option>
                            <el-option label="time" value="time"></el-option>
                            <el-option label="datetime" value="datetime"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="长度" required>
                        <el-input v-model="colform.col_length" autocomplete="off" placeholder="若类型为char或varchar则必填">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth" required>
                        <el-input v-model="colform.description" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="选项" :label-width="formLabelWidth">
                        <el-checkbox v-model="pri_checked">主键</el-checkbox>
                        <el-checkbox v-model="isnull_checked">非空</el-checkbox>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editcolVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editColSubmit">确 定</el-button>
                </div>
            </el-dialog>

            <!-- 编辑业务元数据对话框 -->
            <el-dialog title="编辑信息" :visible.sync="edityewuVisible">
                <el-form :model="yewuform">
                    <el-form-item label="数据表名称" :label-width="formLabelWidth" required>
                        <el-input v-model="yewuform.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="中文名称" :label-width="formLabelWidth" required>
                        <el-input v-model="yewuform.cnname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="分类" :label-width="formLabelWidth" required>
                        <el-select v-model="yewuform.type" placeholder="请选择类型">
                            <el-option label="产品" value="产品"></el-option>
                            <el-option label="网关" value="网关"></el-option>
                            <el-option label="人员" value="人员"></el-option>
                            <el-option label="企业" value="企业"></el-option>
                            <el-option label="其他" value="其他"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责人" :label-width="formLabelWidth" required>
                        <el-input v-model="yewuform.owner" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth" required>
                        <el-input v-model="yewuform.description" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="注意事项" :label-width="formLabelWidth" required>
                        <el-input v-model="yewuform.tip" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="edityewuVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editYewuSubmit">确 定</el-button>
                </div>
            </el-dialog>
        </el-main>
    </el-container>

</template>

<script>
/* eslint-disable */
import axios from 'axios'
import global from '@/components/global'
export default {
    data() {
        return {
            activeName: 'first',
            tableName: '',
            requestData: {},
            requestData2: {},
            nowtable: '',
            tabPosition: 'left',
            ziduanList: [],
            yewuList: [],
            pri_checked: false,
            isnull_checked: false,
            addcolVisible: false,
            editcolVisible: false,
            edityewuVisible: false,
            colform: [],
            yewuform: {},
            editindex: 0
        }
    },
    methods: {
        handleClick(tab, event) {
            console.log(tab.name, event);
            this.activeName = tab.name;
        },
        goback() {
            //this.$router.back();
            this.$router.push({ path: "/tablelist", query: { activeName: "second" } });
        },
        // 新建字段
        addCol() {
            this.colform = []
            this.pri_checked = false
            this.isnull_checked = false
            this.addcolVisible = true
        },
        addColSubmit() { //读取表单数据生成sql语句
            var sql = "alter table " + this.tableName + " add " + this.colform.name + " " + this.colform.type
            if (this.colform.type == "char" || this.colform.type == "varchar") {
                sql = sql + "(" + this.colform.col_length + ")"
            }
            if (this.isnull_checked == true) {
                sql = sql + " not null"
            } else {
                sql = sql + " null"
            }
            if (this.colform.description != "") {
                sql = sql + " COMMENT '" + this.colform.description + "'"
            }
            if (this.pri_checked == true) {
                sql = sql + ","
                var key = "(`" + this.colform.name + "`";
                for (var i = 0; i < this.ziduanList.length; i++) {
                    if (this.ziduanList[i].COLUMN_KEY == "PRI") {
                        key = key + ",`" + this.ziduanList[i].COLUMN_NAME + "`";
                    }
                }
                if (key != "('" + this.colform.name + "'") {
                    sql = sql + "DROP PRIMARY KEY,";
                }
                key = key + ")";
                sql = sql + "ADD PRIMARY KEY " + key + " USING BTREE;"
            } else {
                sql = sql + ";"
            }
            console.log(sql)
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "",
                "sql": sql
            }
            axios({
                url:  "/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {
                this.getziduanList()
                this.addcolVisible = false
                this.$message({
                    message: '创建成功！',
                    type: 'success'
                });
            }).catch((error) => {
                this.$message.error('请检查您的输入是否有误！');
            })
        },
        //刷新业务信息
        getyewuList() {
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "find",
                "sql": "select * from metadata_table where metadata_name='" + this.tableName + "'"
            }
            axios({
                url: "/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {
                if (res.data.data != null) {
                    this.yewuList = JSON.parse(JSON.stringify(res.data.data[0]));
                }
            })
        },
        //刷新字段信息
        getziduanList() {
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "find",
                "sql": "select * from information_schema.COLUMNS where TABLE_SCHEMA='gateway' and TABLE_NAME='" + this.tableName + "'"
            }
            axios({
                url:"/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {
                this.ziduanList = JSON.parse(JSON.stringify(res.data.data));
            })
        },
        //刷新nowtable数据
        getnowtable() {
            this.tableName = this.$route.query.tableName;
            console.log(this.tableName);
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "find",
                "sql": "select * from information_schema.TABLES where TABLE_SCHEMA='gateway' and TABLE_NAME='" + this.tableName + "'"
            }
            axios({
                url: "/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {
                this.nowtable = JSON.parse(JSON.stringify(res.data.data[0]));
                console.log(this.nowtable);
            })
        },
        //删除字段
        deleteCol(index, row) {
            this.$confirm('此操作将永久删除该字段, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.requestData = {
                    "databaseType": global.dbtype,
                    "operate": "",
                    "sql": "alter table " + this.tableName + " drop COLUMN " + row.COLUMN_NAME
                }
                axios({
                    url:  "/request",
                    method: 'POST',
                    dataType: 'json',
                    data: this.requestData
                }).then(res => {
                    this.getziduanList()
                    this.dialogFormVisible = false
                    this.$message({
                        message: '删除成功！',
                        type: 'success'
                    });
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //编辑字段
        editCol(index, row) {
            this.editindex = index
            this.colform.oldname = row.COLUMN_NAME
            this.$set(this.colform, "name", row.COLUMN_NAME)
            this.$set(this.colform, "type", row.DATA_TYPE)
            this.$set(this.colform, "col_length", row.CHARACTER_MAXIMUM_LENGTH)
            this.$set(this.colform, "description", row.COLUMN_COMMENT)
            if (row.COLUMN_KEY == 'PRI') {
                this.pri_checked = true
            } else {
                this.pri_checked = false
            }
            if (row.IS_NULLABLE == 'NO') {
                this.isnull_checked = true
            } else {
                this.isnull_checked = false
            }
            this.editcolVisible = true
        },
        editColSubmit() { //读取表单数据生成sql语句
            var sql = "alter table " + this.tableName + " CHANGE COLUMN `" + this.colform.oldname + "` " + this.colform.name + " " + this.colform.type
            if (this.colform.type == "char" || this.colform.type == "varchar") {
                sql = sql + "(" + this.colform.col_length + ")"
            }
            if (this.isnull_checked == true) {
                sql = sql + " not null"
            } else {
                sql = sql + " null"
            }
            if (this.colform.description != "") {
                sql = sql + " COMMENT '" + this.colform.description + "'"
            }
            if (this.pri_checked == true) {
                sql = sql + ","
                var key = "(`" + this.colform.name + "`";
                var flag = 0
                for (var i = 0; i < this.ziduanList.length; i++) {
                    if (this.ziduanList[i].COLUMN_KEY == "PRI") {
                        flag = 1
                        if (this.ziduanList[i].COLUMN_NAME != this.colform.name) {
                            key = key + ",`" + this.ziduanList[i].COLUMN_NAME + "`";
                        }
                    }
                }
                if (flag == 1) {
                    sql = sql + "DROP PRIMARY KEY,";
                }
                key = key + ")";
                sql = sql + "ADD PRIMARY KEY " + key + " USING BTREE;"
            } else {
                this.ziduanList[this.editindex].COLUMN_KEY = ""
                sql = sql + ",DROP PRIMARY KEY"
                var key = "("
                var flag = 0
                for (var i = 0; i < this.ziduanList.length; i++) {
                    if (this.ziduanList[i].COLUMN_KEY == "PRI") {
                        key = key + "`" + this.ziduanList[i].COLUMN_NAME + "`,"
                        flag = 1
                    }
                }
                key = key.slice(0, key.length - 1)
                key = key + ")"
                if (flag == 1) {
                    sql = sql + ",ADD PRIMARY KEY " + key + " USING BTREE;"
                } else {
                    sql = sql + ";"
                }

            }
            console.log(sql)
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "",
                "sql": sql
            }
            axios({
                url: "/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {

                this.getziduanList()
                this.dialogFormVisible = false
                this.$message({
                    message: '编辑成功！',
                    type: 'success'
                });
                this.editcolVisible = false
                this.colform = []
                this.pri_checked = false
                this.isnull_checked = false


            }).catch((error) => {
                this.$message.error('请检查您的输入是否有误！');
            })
        },
        //编辑业务元数据
        editYewu() {
            this.yewuform.oldname = this.nowtable.TABLE_NAME
            this.$set(this.yewuform, "name", this.nowtable.TABLE_NAME)
            this.$set(this.yewuform, "cnname", this.yewuList.metadata_cnname)
            this.$set(this.yewuform, "type", this.yewuList.metadata_subarea)
            this.$set(this.yewuform, "owner", this.yewuList.metadata_owner)
            this.$set(this.yewuform, "description", this.nowtable.TABLE_COMMENT)
            this.$set(this.yewuform, "tip", this.yewuList.metadata_tip)
            this.edityewuVisible = true

        },
        editYewuSubmit() {
            var operate = 'insert'
            var sql1 = ''
            var sql2 = ''
            var sql3 = '' //读取表单数据生成sql语句
            if (this.yewuList.length != 0) {
                operate = 'update'
            }
            if (operate == 'insert') {
                sql1 = "insert into metadata_table (metadata_name,metadata_cnname,metadata_subarea,metadata_owner,metadata_tip) values ('" +
                    this.yewuform.name + "','" + this.yewuform.cnname + "','" + this.yewuform.type + "','" + this.yewuform.owner + "','" + this.yewuform.tip + "'); "
            } else {
                sql1 = "update metadata_table set metadata_subarea='" + this.yewuform.type +
                    "',metadata_owner='" + this.yewuform.owner +
                    "',metadata_tip='" + this.yewuform.tip +
                    "',metadata_cnname='" + this.yewuform.cnname + "' where metadata_name='" + this.yewuform.oldname + "'; "
            }
            sql3 = "ALTER TABLE " + this.yewuform.oldname + " RENAME TO " + this.yewuform.name + ";"
            sql2 = "alter table " + this.yewuform.oldname + " comment '" + this.yewuform.description + "'; "
            this.requestData = {
                "databaseType": global.dbtype,
                "operate": "",
                "sql": sql1
            }
            console.log(this.requestData.sql)
            axios({
                url:"/request",
                method: 'POST',
                dataType: 'json',
                data: this.requestData
            }).then(res => {
                this.requestData = {
                    "databaseType": global.dbtype,
                    "operate": "",
                    "sql": sql2
                }
                console.log(this.requestData.sql)
                axios({
                    url: "/request",
                    method: 'POST',
                    dataType: 'json',
                    data: this.requestData
                }).then(res => {
                    this.requestData = {
                        "databaseType": global.dbtype,
                        "operate": "",
                        "sql": sql3
                    }
                    console.log(this.requestData.sql)
                    axios({
                        url: "/request",
                        method: 'POST',
                        dataType: 'json',
                        data: this.requestData
                    }).then(res => {

                        this.getyewuList()
                        this.dialogFormVisible = false
                        this.$message({
                            message: '编辑成功！',
                            type: 'success'
                        });
                        this.edityewuVisible = false
                        this.yewuform = {}


                    }).catch((error) => {
                        this.$message.error('请检查您的输入是否有误！');
                    })

                }).catch((error) => {
                    this.$message.error('请检查您的输入是否有误！');
                })

            }).catch((error) => {
                this.$message.error('请检查您的输入是否有误！');
            })
        },
        //删除表
        deleteTable() {
            this.$confirm('此操作将永久删除该数据表, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.requestData = {
                    "databaseType": global.dbtype,
                    "operate": "",
                    "sql": "DROP TABLE " + this.tableName
                }
                axios({
                    url: "/request",
                    method: 'POST',
                    dataType: 'json',
                    data: this.requestData
                }).then(res => {

                    this.requestData = {
                        "databaseType": global.dbtype,
                        "operate": "",
                        "sql": "delete from metadata_table where metadata_name = '" + this.tableName + "'"
                    }
                    axios({
                        url: "/request",
                        method: 'POST',
                        dataType: 'json',
                        data: this.requestData
                    }).then(res => {

                        this.getyewuList()
                        this.dialogFormVisible = false
                        this.$message({
                            message: '删除成功！',
                            type: 'success'
                        });
                        this.goback()
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //表格显示
        stateFormat(row, column) {
            if (row.COLUMN_KEY == "PRI") {
                return '√'
            } else {
                return ''
            }
        },
        stateFormat2(row, column) {
            if (row.IS_NULLABLE == "YES") {
                return '是'
            } else {
                return '否'
            }
        },


    },
    created() {
        this.getnowtable()
        this.getyewuList()
        this.getziduanList()
    }
}
</script>

<style>

</style>
